<?php
namespace App\Services\Chanjet;

use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeSheet;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;


class TplusExcelExport implements WithEvents
{

    //公共导出
    protected $row;
    protected $data;
    protected $template;
    protected $fileName;

    public function __construct(string $template,string $row, array $data,string $fileName)
    {
        $this->row = $row;
        $this->data = $data;
        $this->template = $template;
        $this->fileName = $fileName;
    }
    public function template()
    {
        return storage_path($this->template);
    }

    public function registerEvents(): array
    {

        return [
            BeforeSheet::class => function(BeforeSheet $event) {
//                // 1. 加载模板文件
//                $templatePath = $this->template();
//
//                $spreadsheet = IOFactory::load($templatePath);
//
//                // 2. 获取活动工作表
//                $worksheet = $spreadsheet->getActiveSheet();
//
//                // 3. 替换标题占位符
//                //$worksheet->setCellValue('A1', $this->reportTitle);
//
//                // 4. 写入动态数据
//                foreach ($this->data as $index => $item) {
//                    $row = (int)$this->row + $index;
//                    $worksheet->setCellValue('A'.$row, $item['Code']);
//                    $worksheet->setCellValue('B'.$row, $item['Name']);
//                    $worksheet->setCellValue('C'.$row, $item['disabled']);//0 否 1是
//                    // 添加公式示例
//                    //$worksheet->setCellValue('F'.$row, "=D{$row}*1.1");
//                }
//
//                // 6. 保存修改后的Spreadsheet对象
//                $event->sheet->setSpreadsheet($spreadsheet);

            },
        ];
    }
    public function appendToExcel()
    {
        try {
            // 清除所有输出缓冲区
            while (ob_get_level()) ob_end_clean();

            // 加载或创建表格
            if ($this->template() && file_exists($this->template())) {
                $spreadsheet = IOFactory::load($this->template());
            } else {
                $spreadsheet = new Spreadsheet();
            }

            $worksheet = $spreadsheet->getActiveSheet();
            $lastRow = $worksheet->getHighestRow();

            // 正确计算行号：从最后一行+1开始追加
            foreach ($this->data as $rowIndex => $rowData) {
                $currentRow = $lastRow + 1 + $rowIndex;
                $col = 1;
                foreach ($rowData as $value) {
                    $worksheet->setCellValueByColumnAndRow($col, $currentRow, $value);
                    $col++;
                }
            }

            // 创建临时文件
            $tempFilePath = tempnam(sys_get_temp_dir(), 'excel_') . '.xlsx';

            // 保存到临时文件
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save($tempFilePath);

            // 释放内存
            $spreadsheet->disconnectWorksheets();
            unset($spreadsheet, $writer);

            // 返回下载响应
            //return Excel::download(new CommonExcelExport($row, $exceldata, $datawith), $filename);
            return response()->download(
                $tempFilePath,
                $this->generateFilename(),
                [
                    'Content-Type' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                    'Cache-Control' => 'max-age=0'
                ]
            )->deleteFileAfterSend(true);

        } catch (\Exception $e) {
            // 记录异常并返回错误
            Log::info("Excel导出失败: " . $e->getMessage());
            abort(500, '文件生成失败: ' . $e->getMessage());
        }
    }
    // 检查模板是否存在
    protected function templateExists(): bool
    {
        return file_exists($this->template());
    }

    // 生成下载文件名
    protected function generateFilename(): string
    {
        return $this->fileName.'_' . now()->format('Ymd_His') . '.xlsx';
    }
}
